package com.codegeek.common.utils;

import com.codegeek.common.utils.text.crcUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @功能描述: 字符串操作帮助类
 * @开发人员: 胡鹏
 * @创建日期: 2016-5-15 上午11:41:37
 */
public class myStringUtils {

    static final char TABLE1021[] = { /* CRC1021余式表 */
            0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108,
            0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231,
            0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339,
            0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462,
            0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a,
            0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653,
            0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b,
            0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4,
            0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc,
            0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5,
            0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd,
            0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6,
            0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae,
            0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97,
            0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f,
            0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188,
            0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080,
            0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9,
            0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1,
            0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea,
            0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2,
            0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db,
            0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3,
            0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c,
            0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844,
            0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d,
            0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75,
            0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e,
            0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26,
            0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f,
            0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17,
            0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0};

    //将字节数组转换为16进制字符串
    public static String BinaryToHexString(byte[] bytes) {
        String hexStr = "0123456789ABCDEF";
        String result = "";
        String hex = "";
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result += hex + " ";
        }
        return result;
    }

    //16进制字符串转Int,16进制值转int值
    // hexInt:16进制字符串
    public static int parseIntFromHexString(String hexInt) {
        return Integer.parseInt(hexInt, 16);
    }


    //16进制字符串转Long,16进制值转Long值
    // hexInt:16进制字符串
    public static long parseLongFromHexString(String hexLong) {
        return Long.parseLong(hexLong, 16);
    }

    //int转16进制,1字节表示(2),xx
    public static String numToHex8(int b) {
        return String.format("%02x", b);
    }

    //int转16进制,2字节表示,xxxx
    public static String numToHex16(int b) {
        return String.format("%04x", b);
    }

    //16进制字符串转float
    //hexFloat 高位在前，低位在后
//    public static float parseFloatFromHexString(String hexFloat) {
//        return Float.intBitsToFloat(parseIntFromHexString(hexFloat));
//    }
//
//    //低位在前 高位在后
//    public static float parseFloatFromReverseHexString(String hexFloat) {
//        float result = 0.0f;
//        try {
//            String reverseFloat = hexFloat.substring(4, 8) + hexFloat.substring(0, 4);
//            result = Float.intBitsToFloat(parseIntFromHexString(reverseFloat));
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            return result;
//        }
//    }

    //获取反序字符串
    public static String getReverseString(String in) {
        if (in == null) {
            return null;
        }
        return new StringBuilder(in).reverse().toString();
    }

    //低位在前 高位在后 每个字节低位在前，高位在后
//    public static float parseFloatFromReverseHexString2(String hexFloat) {
//        float result = 0.0f;
//        try {
//            String reverseFloat = hexFloat.substring(6, 8) + hexFloat.substring(4, 6) + hexFloat.substring(2, 4) + hexFloat.substring(0, 2);
//            result = Float.intBitsToFloat(parseIntFromHexString(reverseFloat));
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            return result;
//        }
//    }

    //hex拼接字符串还原
    public static String jointHexStringToString(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        String result = "";
        for (int i = 1; i < hexString.length(); ) {
            result += hexString.charAt(i);
            i += 2;
        }
        return result;
    }

//    public static String buildCrc(String str) {
//        byte[] crc = hexStringToBytes(str);
//        String jiaoyan = Integer.toHexString(getCRC1021(crc, crc.length)).toUpperCase();
//        if (jiaoyan.length() == 3) {
//            jiaoyan = "0" + jiaoyan;
//        } else if (jiaoyan.length() == 2) {
//            jiaoyan = "00" + jiaoyan;
//        }
//        String hexStr = str + jiaoyan + "33";
//        return hexStr;
//    }

//    public static String buildCrc2(String str) {
//        byte[] crc = hexStringToBytes(str);
//        String jiaoyan = Integer.toHexString(getCRC1021(crc, crc.length)).toUpperCase();
//        if (jiaoyan.length() == 3) {
//            jiaoyan = "0" + jiaoyan;
//        } else if (jiaoyan.length() == 2) {
//            jiaoyan = "00" + jiaoyan;
//        }
//        String hexStr = str + jiaoyan + "33";
//        return hexStr;
//    }

    /*
     * 将二进制的字符串转换成十六进制的字符串
     *
     * @param hexString
     * @return
     */
//    public static String binaryStrToHexString(String hexString) {
//
//        if (hexString == null || hexString.equals("") || hexString.length() % 4 != 0) {
//            return null;
//        }
//
//        String hexStr = "0123456789ABCDEF";
//        String result = "";
//        for (int i = 0; i < hexString.length(); ) {
//            String text = hexString.substring(i, i + 4);
//            int index = Integer.parseInt(text, 2);
//            hexStr.charAt(index);
//            result += hexStr.charAt(index);
//            i += 4;
//        }
//
//        return result;
//    }


    /*
     * 将十六进制的字符串转换成二进制的字符串
     *
     * @param hexString
     * @return
     */
    public static String hexStrToBinaryStr(String hexString) {

        if (hexString == null || hexString.equals("")) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        // 将每一个十六进制字符分别转换成一个四位的二进制字符
        for (int i = 0; i < hexString.length(); i++) {
            String indexStr = hexString.substring(i, i + 1);
            String binaryStr = Integer.toBinaryString(Integer.parseInt(indexStr, 16));
            while (binaryStr.length() < 4) {
                binaryStr = "0" + binaryStr;
            }
            sb.append(binaryStr);
        }

        return sb.toString();
    }

    /**
     * 计算crc校验
     *
     * @return
     */
    public static char getCRC1021(byte b[], int len) {
        char crc = 0;
        byte hb = 0;
        int j = 0;
        int index;
        while (len-- != 0) {
            hb = (byte) (crc / 256); //以8位二进制数的形式暂存CRC的高8位
            index = ((hb ^ b[j]) & 0xff); //求得所查索引下标
            crc <<= 8; // 左移8位，相当于CRC的低8位乘以
            crc ^= (TABLE1021[index]); // 高8位和当前字节相加后再查表求CRC ，再加上以前的CRC
            j++;
        }
        return (crc);
    }

    /*
     * 给16进制字符串创建CRC校验
     * @author wj
     * */
    public static String buildCrcEx(String str) {
        byte[] strByte = hexStringToBytes(str);
        Integer num = crcUtil.calcCrc16(strByte);
        String sufferNum = num.toHexString(num).toUpperCase();
        if (sufferNum.length() == 3) {
            sufferNum = "0" + sufferNum;
        } else if (sufferNum.length() == 2) {
            sufferNum = "00" + sufferNum;
        } else if (sufferNum.length() == 1) {
            sufferNum = "000" + sufferNum;
        } else if (sufferNum.length() == 0) {
            sufferNum = "0000";
        }
        str = sufferNum.substring(2, 4) + sufferNum.substring(0, 2);
        return str;
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        // toUpperCase将字符串中的所有字符转换为大写
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        // toCharArray将此字符串转换为一个新的字符数组。
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | (charToByte(hexChars[pos + 1]) & 0xff));
        }
        return d;
    }

    //charToByte返回在指定字符的第一个发生的字符串中的索引，即返回匹配字符
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 下划线 _
     */
    public static final String SPAN = "_";
    /**
     * 斜杠 \
     */
    public static final String SLASH = "\\";
    /**
     * 反斜杠 /
     */
    public static final String BACKSLASH = "/";
    /**
     * 点 .
     */
    public static final String DOT = ".";
    /**
     * 逗号 ,
     */
    public static final String COMMA = ",";
    /**
     * 冒号 :
     */
    public static final String COLON = ":";
    /**
     * @
     */
    public static final String ALT = "@";
    /**
     * 时间格式 yyyy-MM-dd HH24:mm:ss for oracle
     */
    public static final String TIMEFORMAT_DB = "YYYY-MM-DD HH24:MI:SS";
    /**
     * 时间格式 yyyy-MM-dd HH:mm:ss
     */
    public static final String TIMEFORMAT = "yyyy-MM-dd HH:mm:ss";
    /**
     * 时间格式 yyyyMMddHHmmss
     */
    public static final String MINITIMEFORMAT = "yyyyMMddHHmmss";
    /**
     * 时间格式 yyyyMMddHH24mmss for oracle
     */
    public static final String MINITIMEFORMAT_DB = "yyyyMMddHH24miss";
    /**
     * remote 返回结果集，默认分页每页数据集大小
     */
    public static final int pageSize = 50;
    /**
     * 空字符串 ""
     */
    public static final String EMPTY = "";
    /**
     * 空格 " "
     */
    public static final String BLANK = " ";
    /**
     * 双下划线 "__"
     */
    public static final String DOUBLE_DASH_SEPERATOR = "__";
    public static final String TMPFILEEXT = "tmp";

    /**
     * 判断的指定的变量是否为空
     *
     * @param t 需要判断的字符串
     * @return 如为 null 范围 “”，如不为null，范围实际内容
     */
    public static String checkNull(String t) {
        if (t == null) {
            return "";
        } else {
            return t;
        }
    }

    /**
     * @功能描述: TODO(这里用一句话描述这个方法的作用)
     * @输入参数: @param t
     * @输入参数: @return
     * @返回描述:
     * @异常类型:
     */
    public static String checkNullObj(Object t) {
        if (t == null) {
            return "";
        } else {
            return (String) t;
        }
    }

//    private static DateFormat df = new SimpleDateFormat(TIMEFORMAT);

    /**
     * 将时间类型变量转换为字符串，格式 yyyy-MM-dd HH24:mi:ss
     *
     * @param d 要转换的日期
     * @return 转换后的字符串 yyyy-MM-dd HH24:mi:ss 格式
     */
//    public static String time2str(Date d) {
//        return df.format(d);
//    }

    /**
     * 按指定格式将时间类型变量转换为字符串
     *
     * @param d      要转换的日期
     * @param format 要转换的字符串格式
     * @return 转换后的字符串
     */
    public static String time2str(Date d, String format) {
        DateFormat dft = new SimpleDateFormat(format);
        return dft.format(d);
    }

    /**
     * 将指定格式字符串转换为日期类型，默认输入字符串格式：yyyy-MM-dd HH:mm:ss
     *
     * @param s 要转换的字符串
     * @return 转换后的日期变量
     * @throws ParseException 格式不对抛出异常
     */
//    public static Date str2date(String s) throws ParseException {
//        return df.parse(s);
//    }

    /**
     * 将指定格式字符串转换为日期类型
     *
     * @param s      要转换的字符串
     * @param format 要转换的字符串格式
     * @return 转换后的日期变量
     * @throws ParseException 格式不对抛出异常
     */
    public static Date str2date(String s, String format) throws ParseException {
        DateFormat dft = new SimpleDateFormat(format);
        return dft.parse(s);
    }

    /**
     * 空属性 Properties() 对象
     */
    protected static final Properties EMPTY_PROPERTIES = new Properties();

    /**
     * 把以空格分隔的key value pair组成的字符串转换为属性 如：fileName=a.txt taskId =123
     *
     * @param args
     * @return
     */
    public static Properties parseArgs(String args) {
        if (args != null) {
            args = checkNull(args);
            return parseArgs(args.split(","));
        }
        return EMPTY_PROPERTIES;
    }

    /**
     * 把key value pair组成的字符串数组转换为属性 如：fileName=a.txt
     *
     * @param args
     * @return
     */
    public static Properties parseArgs(String[] args) {

        if (args == null || args.length < 1) {
            return EMPTY_PROPERTIES;
        }

        Properties p = new Properties();

        for (int i = 0; i < args.length; i++) {
            String[] strings = args[i].split("=");
            p.setProperty(strings[0].trim(), strings[1].trim());
        }
        return p;
    }

    static String localHostIP = null;

    public static String getLocalHostIPByNet() {
        if (localHostIP == null) {
            try {
                // 根据网卡取本机配置的IP
                Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
                        .getNetworkInterfaces();
                while (e1.hasMoreElements()) {
                    NetworkInterface ni = (NetworkInterface) e1.nextElement();
                    if (!ni.getName().equals("eth3")) {
                        continue;
                    } else {
                        Enumeration<?> e2 = ni.getInetAddresses();
                        while (e2.hasMoreElements()) {
                            InetAddress ia = (InetAddress) e2.nextElement();
                            if (ia instanceof Inet6Address) {
                                continue;
                            }
                            localHostIP = ia.getHostAddress();
                        }
                        break;
                    }
                }
            } catch (SocketException ex) {
                // Log.error("获取本机IP地址出错：" + ex.getMessage(), ex);
            }
        }
        return localHostIP;
    }

    public static String getLocalHostIP() {
        if (localHostIP == null) {
            try {
                Enumeration allNetInterfaces = NetworkInterface
                        .getNetworkInterfaces();
                InetAddress ip = null;
                while (allNetInterfaces.hasMoreElements()) {
                    NetworkInterface netInterface = (NetworkInterface) allNetInterfaces
                            .nextElement();
                    System.out.println(netInterface.getName());
                    Enumeration addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = (InetAddress) addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            localHostIP = ip.getHostAddress();
                            String tt = netInterface.getName();
                        }
                    }
                }
            } catch (SocketException ex) {

                // Log.error("获取本机IP地址出错：" + ex.getMessage(), ex);
            }
        }
        return localHostIP;
    }

    private static Properties configInfo = null;

    /**
     * 将指定的文件名格式转换为正则表达式
     *
     * @param str
     * @return
     */
    public static String convert2regEx(String str) {
        String regExp = str;
        regExp = regExp.replace('.', '#');
        regExp = regExp.replaceAll("#", "\\\\.");
        regExp = regExp.replace('*', '#');
        regExp = regExp.replaceAll("#", ".*");
        regExp = regExp.replace('?', '#');
        regExp = regExp.replaceAll("#", ".?");
        regExp = "^" + regExp + "$";
        return regExp;
    }

    /**
     * 日期偏移后返回字条字符串
     *
     * @param date
     * @param format
     * @param addHour
     * @return
     */
    public static String GetDateString(Date date, String format, int addHour) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, addHour);
        DateFormat df = new SimpleDateFormat(format);// ("yyyyMMddHHmm");
        return df.format(cal.getTime());
    }

    /**
     * 判断字符串是否为空
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        return s == null || s.trim().length() == 0;
    }

    public static boolean isEmptys(String... args) {
        if (args == null) {
            return true;
        }
        for (String s : args) {
            if (isEmpty(s)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断字符是否为字母
     *
     * @param c
     * @return
     */
    public static boolean isLetter(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    }

    /**
     * 判断字符是否为数字
     *
     * @param c
     * @return
     */
    public static boolean isDigit(char c) {
        return (c >= '0' && c <= '9');
    }

    /**
     * 计算字符串中给定字符出现的次数
     *
     * @param str
     * @param c
     * @return
     */
    public static int count(String str, char c) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == c) {
                count++;
            }
        }
        return count;
    }

    /**
     * 将字符串的首字母大写
     *
     * @param s
     * @return
     */
    public static String upperCaseFirstChar(String s) {
        if (s == null || s.length() <= 0) {
            return s;
        }
        StringBuffer sb = new StringBuffer();
        sb.append(s.substring(0, 1).toUpperCase());
        sb.append(s);
        sb.deleteCharAt(1);
        return sb.toString();
    }

    /**
     * 将小写字母转化为大写字母
     *
     * @param c
     * @return
     */
    public static char toUpperCase(char c) {
        if (c >= 'a' && c <= 'z') {
            return (char) (c - 32);
        }
        return c;
    }

    /**
     * 将大写字母转化为小写字母
     *
     * @param c
     * @return
     */
    public static char toLowerCase(char c) {
        if (c >= 'A' && c <= 'Z') {
            return (char) (c + 32);
        }
        return c;
    }

    /**
     * 判断字符是否为空字符
     *
     * @param c
     * @return
     */
    public static boolean isBlank(char c) {
        return c == ' ' || c == '\t' || c == '\r' || c == '\n';
    }

    /**
     * 将byte数组中指定的部分转化为字符串
     *
     * @param buf   byte数组
     * @param first 第一个byte的位置
     * @param last  最后一个byte的位置
     * @return
     */
    public static String valueOf(byte[] buf, int first, int last) {
        int start = first;
        for (; start < last; start++) {
            if (buf[start] != 0) {
                break;
            }
        }

        int end = last - 1;
        for (; end >= start; end--) {
            if (buf[end] != 0) {
                break;
            }
        }

        if (end < start) {
            return null;
        }
        return new String(buf, start, end + 1);
    }

    /**
     * 将byte数组转化为字符串
     *
     * @param buf byte数组
     * @return
     */
    public static String valueOf(byte[] buf) {
        return valueOf(buf, 0, buf.length);
    }

    /**
     * 将BigDecimal转化为字符串
     *
     * @param b
     * @param scale 小数位数
     * @return
     */
    public static String valueOf(BigDecimal b, int scale) {
        int n = 0;
        String s = b.setScale(scale, RoundingMode.HALF_UP).toString();
        int dotidx = s.indexOf(".");
        if (dotidx == -1) {
            s = s + ".";
            n = scale;
            dotidx = s.length() - 1;
        } else {
            n = scale - (s.length() - dotidx - 1);
        }
        if (scale == 0) {
            return s.substring(0, dotidx);
        }

        return append(s, n, '0');
    }

    /**
     * 计算字符串的长度
     *
     * @param s
     * @return
     */
    public static int size(String s) {
        int size = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c > 0x7F) {
                size += 2;
            } else {
                size += 1;
            }
        }
        return size;
    }

    /**
     * 在字符串后追加空格，使其长度达到n
     *
     * @param s 原始字符串
     * @param n 结果字符串的长度
     * @return
     */
    public static String append(String s, int n) {
        return append(s, n, ' ');
    }

    /**
     * 在字符串后追加字符c，使其长度达到n
     *
     * @param s 原始字符串
     * @param n 结果字符串的长度
     * @return
     */
    public static String append(String s, int n, char c) {
        StringBuilder sb = new StringBuilder(s);
        for (int i = 0; i < n; i++) {
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 在字符串左边添加空格，使其长度达到n
     *
     * @param s 原始字符串
     * @param n 结果字符串的长度
     * @return
     */
    public static String lpad(String s, int n) {
        return lpad(s, n, ' ');
    }

    /**
     * 在字符串右边添加空格，使其长度达到n
     *
     * @param s 原始字符串
     * @param n 结果字符串的长度
     * @return
     */
    public static String rpad(String s, int n) {
        return rpad(s, n, ' ');
    }

    /**
     * 在字符串左边添加指定字符串，使其长度达到n
     *
     * @param s      原始字符串
     * @param n      结果字符串的长度
     * @param padStr 需要添加的字符串
     * @return
     */
    public static String lpad(String s, int n, String padStr) {
        StringBuilder sb = new StringBuilder();
        int pad = n - s.length();

        if (padStr.length() == 0) {
            padStr = " ";
        }
        int times = pad / padStr.length();
        int remain = pad % padStr.length();
        for (int i = 0; i < times; i++) {
            sb.append(padStr);
        }

        if (remain != 0) {
            sb.append(padStr.substring(0, remain));
        }
        sb.append(s);

        return sb.toString();
    }

    /**
     * 在字符串右边添加指定字符串，使其长度达到n
     *
     * @param s      原始字符串
     * @param n      结果字符串的长度
     * @param padStr 需要添加的字符串
     * @return
     */
    public static String rpad(String s, int n, String padStr) {
        StringBuilder sb = new StringBuilder(s);

        if (padStr.length() == 0) {
            padStr = " ";
        }
        int pad = n - s.length();
        int times = pad / padStr.length();
        int remain = pad % padStr.length();
        for (int i = 0; i < times; i++) {
            sb.append(padStr);
        }

        if (remain != 0) {
            sb.append(padStr.substring(0, remain));
        }

        return sb.toString();
    }

    /**
     * 在字符串左边添加指定字符，使其长度达到n
     *
     * @param s 原始字符串
     * @param n 结果字符串的长度
     * @param c 需要添加的字符
     * @return
     */
    public static String lpad(String s, int n, char c) {
        StringBuilder sb = new StringBuilder();
        int size = size(s);
        int pad = n - size;
        for (int i = 0; i < pad; i++) {
            sb.append(c);
        }
        sb.append(s);
        return sb.toString();
    }

    /**
     * 在字符串右边添加指定字符，使其长度达到n
     *
     * @param s 原始字符串
     * @param n 结果字符串的长度
     * @param c 需要添加的字符
     * @return
     */
    public static String rpad(String s, int n, char c) {
        StringBuilder sb = new StringBuilder(s);
        int size = size(s);
        int pad = n - size;
        for (int i = 0; i < pad; i++) {
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 将整形数转化为16进制字符串
     *
     * @param n
     * @return
     */
    public static String byte2Hex(int n) {
        final char[] HS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 2; i++) {
            int h = (n >> i * 4) & 0xf;
            sb.append(HS[h]);
        }
        return sb.toString();
    }

    /**
     * 从字符串中删除指定的字符
     *
     * @param s 原始字符串
     * @param c 需要删除的字符
     * @return
     */
    public static String filter(String s, char c) {
        return filter(s, new char[]{c});
    }

    /**
     * 从字符串中删除所有指定的字符
     *
     * @param s      原始字符串
     * @param filter 需要删除的所有字符
     * @return
     */
    public static String filter(String s, String filter) {
        char[] ca = new char[filter.length()];
        for (int i = 0; i < filter.length(); i++) {
            ca[i] = filter.charAt(i);
        }
        return filter(s, ca);
    }

    /**
     * 从字符串中删除所有指定的字符
     *
     * @param s  原始字符串
     * @param ca 需要删除的所有字符数组
     * @return
     */
    public static String filter(String s, char[] ca) {
        StringBuilder sb = new StringBuilder();
        for (int start = 0; start < s.length(); start++) {
            char ch = s.charAt(start);
            if (!contains(ca, ch)) {
                sb.append(ch);
            }
        }
        return sb.toString();
    }

    /**
     * 将字符串首尾两端的字符c删除
     *
     * @param s 原始字符串
     * @param c 指定字符
     * @return
     */
    public static String trim(String s, char c) {
        return trim(s, new char[]{c});
    }

    /**
     * 将字符串首尾两端的空字符删除
     *
     * @param s 原始字符串
     * @return
     */
    public static String trim(String s) {
        return trim(s, new char[]{' ', '\t', '\r', '\n'});
    }

    /**
     * 将字符串首尾两端的所有字符删除
     *
     * @param s  原始字符串
     * @param ca 指定字符数组
     * @return
     */
    public static String trim(String s, char[] ca) {
        int start = 0;
        for (; start < s.length(); start++) {
            if (!contains(ca, s.charAt(start))) {
                break;
            }
        }

        int end = s.length() - 1;
        for (; end >= start; end--) {
            if (!contains(ca, s.charAt(end))) {
                break;
            }
        }

        if (end < start) {
            return "";
        }
        return s.substring(start, end + 1);
    }

    public static String[] split(String s, String regex) {
        String[] sa = s.split(regex);
        ArrayList<String> list = new ArrayList<String>(sa.length);

        for (int i = 0; i < sa.length; i++) {
            if (sa[i] == null || sa[i].length() == 0) {
                continue;
            }
            list.add(sa[i]);
        }
        return list.toArray(new String[0]);
    }

    /**
     * 判断字符数组中是否包含给定字符
     *
     * @param ca 字符数组
     * @param c  给定字符
     * @return
     */
    private static boolean contains(char[] ca, char c) {
        for (int i = 0; i < ca.length; i++) {
            if (ca[i] == c) {
                return true;
            }
        }
        return false;
    }

    /**
     * 将字符串转化为正则表达式
     *
     * @param s
     * @return
     */
    public static String toRegex(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (myStringUtils.isLetter(c)) {
                sb.append("[");
                sb.append(myStringUtils.toLowerCase(c));
                sb.append(myStringUtils.toUpperCase(c));
                sb.append("]");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * @param col
     * @param regex
     * @return
     * @Method collect2String
     * @Description String集合转String，以regex分隔
     */
    public static String collect2String(Collection<String> col, String regex) {
        Iterator it = col.iterator();
        StringBuilder sb = new StringBuilder();
        while (it.hasNext()) {
            String str = (String) it.next();
            sb.append(regex);
            sb.append(str);
        }
        return sb.toString().substring(1);
    }

    /**
     * @param col
     * @param
     * @return
     * @Method collect2String
     * @Description String集合转String，以regex分隔
     */
    public static String sqlCollect2String(Collection<String> col) {
        Iterator it = col.iterator();
        StringBuilder sb = new StringBuilder();
        while (it.hasNext()) {
            String str = (String) it.next();
            sb.append(",");
            sb.append("'" + str + "'");
        }
        return sb.toString().substring(1);
    }

    /**
     * @param col
     * @return
     * @Method collect2String
     * @Description String集合转String，以regex分隔
     */
    public static String getSqlWhereFiled(String col, String value) {
        if (value != null && !value.trim().isEmpty()) {
            return " and " + col + "='" + value + "' ";
        }
        return "";
    }


//    public static String toUtf8(String src) {
//        String out = "";
//        try {
//            out = URLDecoder.decode(src, "utf-8");
//        } catch (UnsupportedEncodingException e2) {
//            // TODO Auto-generated catch block
//            e2.printStackTrace();
//        }
//        return out;
//    }

    /**
     * JAVA判断字符串数组中是否包含某字符串元素
     *
     * @param substring 某字符串
     * @param source    源字符串数组
     * @return 包含则返回true，否则返回false
     */
    public static boolean isInList(String substring, String[] source) {
        if (source == null || source.length == 0 || substring == null) {
            return false;
        }
        for (int i = 0; i < source.length; i++) {
            String aSource = source[i];
            if (aSource.equals(substring)) {
                return true;
            }
        }
        return false;
    }

    //判断参数种是否有空字符传
    public static boolean isHaveEmpty(String... args) {
        if (args == null || args.length <= 0) {
            return false;
        }
        for (int i = 0; i < args.length; i++) {
            String aSource = args[i];
            if (isEmpty(aSource)) {
                return true;
            }
        }
        return false;
    }

    public static String getDateTimeNow() {
        Calendar now = Calendar.getInstance();
        String year = String.valueOf(now.get(Calendar.YEAR));
        int month = now.get(Calendar.MONTH) + 1;
        int day = now.get(Calendar.DAY_OF_MONTH);
        String dayOfWeek = "0" + now.get(Calendar.DAY_OF_WEEK);
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int minute = now.get(Calendar.MINUTE);
        int second = now.get(Calendar.SECOND);
        String time = year;
        if (month < 10) {
            time += "0" + month;
        } else {
            time += month;
        }
        if (day < 10) {
            time += "0" + day;
        } else {
            time += day;
        }
        time += dayOfWeek;
        if (hour < 10) {
            time += "0" + hour;
        } else {
            time += hour;
        }
        if (minute < 10) {
            time += "0" + minute;
        } else {
            time += minute;
        }
        if (second < 10) {
            time += "0" + second;
        } else {
            time += second;
        }
        return time;
    }

    //获取当前时间字符串，时间字符串格式:yyyy-MM-dd HH:mm:ss
    public static String getDateTimeStr() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sdf.format(new Date());
    }

    public static String appendStartZero(int len, String str) {
        for (int i = str.length(); i < len; i++) {
            str = "0" + str;
        }
        return str;
    }


    //sum校验
    public static String makeChecksum(String hexdata) {
        if (hexdata == null || hexdata.equals("")) {
            return "00";
        }
        hexdata = hexdata.replaceAll(" ", "");
        int total = 0;
        int len = hexdata.length();
        if (len % 2 != 0) {
            return "00";
        }
        int num = 0;
        while (num < len) {
            String s = hexdata.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }

        String strTotal = hexInt(total);
        strTotal = strTotal.substring(strTotal.length() - 2);
        return strTotal;
    }

    private static String hexInt(int total) {
        int a = total / 256;
        int b = total % 256;
        if (a > 255) {
            return hexInt(a) + format(b);
        }
        return format(a) + format(b);
    }

    private static String format(int hex) {
        String hexa = Integer.toHexString(hex);
        int len = hexa.length();
        if (len < 2) {
            hexa = "0" + hexa;
        }
        return hexa;
    }

}
